import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from common.functions import open_browser


class Base:
    def __init__(self, browser):
        # 初始化浏览器
        self.driver = open_browser(browser)
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)

    # 访问url
    def get(self, url):
        try:
            self.driver.get(url)
        except Exception as e:
            print('输入的网址有误,请检查URL')

    # 刷新
    def refresh(self):
        self.driver.refresh()

    # 后退
    def back(self):
        self.driver.back()

    # 前进
    def forward(self):
        self.driver.forward()

    # 元素定位的显示等待
    def find_element(self, locator, timeout=5):
        try:
            return WebDriverWait(self.driver, timeout=timeout).until(EC.presence_of_element_located(locator))
        except Exception as e:
            print('元素定位失败')

    # 获取属性
    def get_attribute(self, locator, attribute):
        ele = self.find_element(locator)
        if ele is not None:
            attr = ele.get_attribute(attribute)
            return attr
        else:
            print('元素定位失败')

    def select(self, locator, i):
        # 获取下拉框 用value的方法,索引的方法
        s = self.find_element(locator)
        select = Select(s)
        if select:
            return select.select_by_value(i)
        else:
            print('定位元素失败')

    # 获取标签文本的方法
    def get_element_text(self, locator):
        ele = self.find_element(locator)
        if ele is not None:
            return ele.text

    # 发送文本
    def send_keys(self, locator, text):
        ele = self.find_element(locator)
        if ele is not None:
            ele.send_keys(text)
        else:
            print('元素定位失败')

    # 点击
    def click(self, locator):
        ele = self.find_element(locator)
        if ele is not None:
            ele.click()
        else:
            print('元素定位失败')

    # 退出浏览器
    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element((By.ID, 'kw')).send_keys('python')
    base.click((By.ID, 'su'))
    time.sleep(3)
    base.refresh()
    time.sleep(2)
    base.back()
    time.sleep(2)
    base.forward()
    time.sleep(2)
    base.get_attribute((By.ID, 'kw'), 'outerHTML')
    base.quit()